import util from '../../utils/util';
import api from "../../utils/api";
import constant from "../../utils/constant";

Page({
    data: {
        MINIO_COURSE_COVER: constant.MINIO_COURSE_COVER, // 课程封面路径
        pageInfo: {pageNum: 1, pageSize: 12, totalPage: 0, totalRow: 0}, // 分页信息
        courses: null, // 课程列表对象
        title: 'JB', // 课程标题
    },

    // 分页搜索课程记录
    page: function () {
        let that = this;
        let title = that.data.title;
        let pageNum = that.data.pageInfo['pageNum'];
        let pageSize = that.data.pageInfo['pageSize'];

        // 请求数据
        let params = {pageNum, pageSize, title: title.trim()};
        api.get('course', '/page', params).then(res => {
            that.setData({
                'courses': pageNum === 1 ? res['records'] : that.data.courses.concat(res['records']),
                'pageInfo.pageNum': res['pageNumber'],
                'pageInfo.pageSize': res['pageSize'],
                'pageInfo.totalPage': res['totalPage'],
                'pageInfo.totalRow': res['totalRow'],
            });
        }).catch(err => util.error('课程查询失败', err));
    },

    // 列表触底时
    onListEnd: function () {
        let that = this;
        let pageNum = that.data.pageInfo['pageNum'];
        let totalPage = that.data.pageInfo['totalPage'];
        if (pageNum < totalPage) {
            this.setData({'pageInfo.pageNum': pageNum + 1});
            this.page();
        }
    },

    // 按课程标题搜索课程
    searchByTitle: function (ev) {
        this.setData({
            'title': ev.detail,
            'pageInfo.pageNum': 1,
        });
        this.page();
    },

    // 取消搜索
    cancelSearch: function (ev) {
        this.setData({
            'title': 'JB',
            'pageInfo.pageNum': 1,
        });
        this.page();
    },

    // 查看课程详情
    showDetail: function (ev) {
        let courseId = ev.currentTarget.dataset['courseId'];
        util.page('/pages/course/detail/detail?courseId=' + courseId, false);
    },

    // 加载函数
    onLoad: function (options) {
        this.page();
        this.getTabBar().setData({"activeTab": 1});
    }
});